import httpService, { RequestParam } from './request';
import http from '@ohos.net.http';
import { promptAction } from '@kit.ArkUI';
import { dMultiIO, node, execStat, multiIO, replacer } from '../utils/taskGraphInterface'

let SEARCH_URL =
  "https://api.bochaai.com/v1/web-search"
let GENERATION_URL =
  "https://api.bochaai.com/v1/ai-search"
let TAG = "_:_WebSearch"

export default class WebSearchManager {
  private requestOptions: http.HttpRequestOptions = {}

  InitParam(dataj) {
    this.requestOptions = {
      method: http.RequestMethod.POST,
      header: {
        'Authorization': 'Bearer sk-3b7267f895dd4b51949247f1ed97227e',
        'Content-Type': 'application/json'
      },
      extraData: JSON.stringify(dataj)
    }
  }

  parseWebSearchResult(result: string): multiIO {
    let TAG = "_:_[parseResultWebSearch]"
    let mio: multiIO = dMultiIO()
    console.log(TAG, "rawresult is ", result)
    if (result.includes("error_msg")) {
      promptAction.showToast({
        "message": result, "duration": 5000
      })
    }
    try {
      let resultj = JSON.parse(result)
      resultj["data"]["webPages"]["value"].map((page) => {
        mio.text += page["name"] + ":" + page["snippet"] + "\n"
      })
      mio.imgPath = resultj["data"]["images"]["value"][0]["contentUrl"]
      return mio
    } catch (e) {
      console.error(TAG, "parseResult", e)
      mio.text = JSON.stringify(e)
      return mio
    }
  }

  async WebSearch(querystr: string): Promise<multiIO> {
    console.log(TAG, "entered", querystr)
    this.InitParam({
      "query": querystr,
      "count": 2
    })
    console.log(TAG, "inited", JSON.stringify(this.requestOptions))
    return await httpService.requestMain(SEARCH_URL, this.requestOptions, (response) => {
      return this.parseWebSearchResult(response)
    })
  }

  parseLLMSearchResult(result: string): multiIO {
    let TAG = "_:_[parseResultLLMSearch]"
    let mio: multiIO = dMultiIO()
    console.log(TAG, "rawresult is ", result)
    if (result.includes("error_msg")) {
      promptAction.showToast({
        "message": result, "duration": 5000
      })
    }
    try {
      let resultj = JSON.parse(result)
      let webpageMSG = resultj["messages"].find(message => message.content_type == "webpage")
      if (webpageMSG) {
        let webpagej = JSON.parse(webpageMSG["content"])
        // mio.text += "webPage search:\n"
        // webpagej["value"].map((page) => {
        //   mio.text += page["name"] + ":" + page["snippet"] + "\n"
        // })
      }
      console.log(TAG,"webpageMSG",JSON.stringify(webpageMSG))
      console.log(TAG,"webpageMSG",mio.text.replace(/\n/g,""))
      let answerMSG = resultj["messages"].find(message => message.content_type == "text")
      if (answerMSG) {
        mio.text +=  answerMSG["content"]
      }
      console.log(TAG,"answerMSG",JSON.stringify(answerMSG))
      console.log(TAG,"answerMSG",mio.text.replace(/\n/g,""))
      let imgMSG = resultj["messages"].find(message => message.content_type == "image")
      if (imgMSG) {
        let imgj = JSON.parse(imgMSG["content"])
        mio.imgPath = imgj["value"][0]["contentUrl"]
      }
      console.log(TAG,"imgMSG",JSON.stringify(imgMSG))
      console.log(TAG,"imgMSG",mio.imgPath.replace(/\n/g,""))
      return mio
    } catch (e) {
      console.error(TAG, "parseResult", e)
      mio.text = JSON.stringify(e)
      return mio
    }
  }

  async LLMSearch(querystr: string): Promise<multiIO> {
    console.log(TAG, "entered llmsearch", querystr)
    this.InitParam({
      "query": querystr,
      "stream": false
    })
    console.log(TAG, "inited llmsearch", JSON.stringify(this.requestOptions))
    return await httpService.requestMain(GENERATION_URL, this.requestOptions, (response) => {
      return this.parseLLMSearchResult(response)
    })
  }
}
